package com.blogspot.nhu313.myhistory.category;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.blogspot.nhu313.myhistory.category.to.Category;
import com.blogspot.nhu313.myhistory.category.to.CategoryFactory;
import com.blogspot.nhu313.myhistory.service.db.DBFactory;
import com.blogspot.nhu313.myhistory.service.db.DBService;

public class CategoryService {
	DBService dbService;
	
	private static final String CLASS_NAME = CategoryService.class.getSimpleName();
	
	public CategoryService(Context context){
		dbService = DBFactory.getDBService(context);
	}

	/**
	 * @param category
	 * @return Category unique ID
	 */
	public long saveCategory(Category category){
		Log.i(CLASS_NAME, "Saving categories" + category.toString());
		ContentValues initialValues = new ContentValues();
		initialValues.put(CategoryFieldName.name.name(), category.getName());
		initialValues.put(CategoryFieldName.parent_id.name(), category.getParentId());
		long id = dbService.add(CategorySQLStringBuilder.TABLE_NAME, initialValues);
		return id;
	}
	
	public List<Category> getCategories(int parentCategoryId){
		Log.i(CLASS_NAME, "Retrieving categories");
		dbService.open();
		Cursor cursor =  dbService.get(CategorySQLStringBuilder.getCategories(parentCategoryId));
		final int size = cursor.getCount();
		List<Category> categories = new ArrayList<Category>(size);
		if (cursor.moveToFirst()){
			for (int i = 0; i < size; i++) {
				Category category = readCategoryData(cursor);
				categories.add(category);
				cursor.moveToNext();
			}
		}
		cursor.close();
		dbService.close();
		return categories;
	}

	private Category readCategoryData(Cursor cursor) {
		int categoryId = cursor.getInt(CategoryFieldName._id.ordinal());
		String categoryName = cursor.getString(CategoryFieldName.name.ordinal());
		int parentId = cursor.getInt(CategoryFieldName.parent_id.ordinal());
		
		Category category = CategoryFactory.createSubCategoryWithId(categoryId, categoryName, parentId);
		Log.i(CLASS_NAME, category.toString());
		return category;
	}
}
